package com.example.logTracer.filter;

import org.apache.commons.lang3.StringUtils;
import com.example.logTracer.SnowflakeId;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Describe : 日志过滤器 对于请求入流请求头进行处理
 * @Author : zyx
 * @Date : 2023/10/8 14:00
 * @Version : 1.0
 **/
@Component
public class LogFilter implements Filter {

    private static final String TRACE_ID = "traceId";
    private static final String SPAN_ID = "spanId";

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String traceId = request.getHeader(TRACE_ID.toLowerCase());
        String spanId = request.getHeader(SPAN_ID.toLowerCase());

        if (StringUtils.isEmpty(traceId)){
            traceId = String.valueOf(SnowflakeId.getInstance().getNextId());
        }
        if (StringUtils.isEmpty(spanId)){
            spanId = "0";
        }else {
            Integer spanIdInt = Integer.valueOf(spanId);
            spanId = String.valueOf(spanIdInt+1);
        }

        MDC.put(TRACE_ID,traceId);
        MDC.put(SPAN_ID,spanId);

        response.setHeader(TRACE_ID,traceId);
        response.setHeader(SPAN_ID,spanId);

        try {
            filterChain.doFilter(servletRequest,servletResponse);
        }finally {
            MDC.clear();
        }
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }

}
